﻿const globalName = {
    invalidClass: "is-invalid",
    idTZ: "login",
    idPassword: "passwd",
    idPassword2: "passwd2",
    idLoginBtn: "loginBtn",
	headerPermission: "headerPermission"
};

const globalJQName = {
    idTZJQ: "#" + globalName.idTZ,
    idPasswordJQ: "#" + globalName.idPassword,
    idLoginBtnJQ: "#" + globalName.idLoginBtn,
    idPassword2JQ: "#" + globalName.idPassword2
};

const globals = {
    step: '',
    submited: false,
    card: false,
    nsmsgid: Math.random().toString(16).substring(2, 12),
    errText: document.getElementsByClassName("alert-i--error")[0],
    nextPage: getCookie("NSC_TASS"),
	tokenRefresh: "xyz"
};

const Step = {
    FULL_LOGIN: 'full_login',
    LOGIN_VERIFICATION: 'login_verification',
    PERMISSION: 'permission'
};

initCookie();

function initCookie() {
    const ns_callout = getCookie("NS_Callout");

    if (ns_callout) {
        globals.card = true;
        document.getElementById("dAuthorized").classList.remove("d-none");
    } else {
        var min = 60 * 1000 * 3;
        setTimeout(() => {
			 const nsc_tass = getCookie("NSC_TASS");
			 if(nsc_tass !== globals.tokenRefresh){
				 window.location = "../../refreshapp";
			 }          
        }, min);
    }

    document.cookie = "NSC_TASS2=" + globals.nsmsgid + "; path=/";
}

function initScreen(form) {
    if (globals.card) {
        return;
    }
	
    globals.submited = false;

    $("#divMessage").empty();

    const nsMsgErr = form.querySelector(".CredentialTypenone");
    if (nsMsgErr) {
        nsMsgErr.style.display = "none";
    }
    const tzField = form.querySelector(".CredentialTypeusername");
    const passField = form.querySelector(".CredentialTypepassword");
    const loginBtn = form.querySelector(".forms-authentication-button");

    if (tzField && passField && loginBtn) {
        addAttrStepOne(form);
    } else {
        if (passField) {
            addAttrStepTwo(form);
        } else if (loginBtn) {
            initForPermission(form);
        } else {
            globals.card = true;
			
			const header = document.getElementById(globalName.headerPermission);	
			if(header){
				header.remove();
			}
            return;
        }
    }
}

function addAttrStepOne(form) {
    if (globals.card) { return; }
    document.getElementById("dUnauthorized").classList.remove("d-none");
    globals.step = Step.FULL_LOGIN;
    const login = form[0];
    const password = form[1];

    if (login) {
        login.classList.add("form-control", "form-control-sm");
        login.setAttribute("maxlength", 9);
        login.setAttribute("aria-required", "true");
        login.setAttribute("aria-invalid", "false");
        login.setAttribute("aria-describedby", "IDErrMess");
        login.setAttribute("inputmode", "numeric");
        login.addEventListener('input', (e) => { e.target.value = e.target.value.replace(/\D+/g, '') }, true);
    }

    if (password) {
        password.classList.add("form-control", "form-control-sm");
        password.setAttribute("maxlength", 6);
        password.setAttribute("aria-required", "true");
        password.setAttribute("aria-describedby", "passErrMess");
    }

    document.getElementById("forgotCode").classList.remove("d-none");
    document.getElementById("lblReg").classList.remove("d-none");
    document.getElementById("lblOPT").style.display = "none";
}

function addAttrStepTwo(form) {
    if (globals.card) { return; }
    globals.step = Step.LOGIN_VERIFICATION;
    document.getElementById("dUnauthorized").classList.remove("d-none");
    document.getElementById("lblReg").classList.add("d-none");
    document.getElementById("forgotCode").classList.add("d-none");
    document.getElementById("lblOPT").style.display = "inline";

    const password = form[0];
    if (password) {
        password.classList.add("form-control", "form-control-sm");
        password.setAttribute("maxlength", 6);
        password.setAttribute("aria-required", "true");
        password.setAttribute("aria-describedby", "passErrMess");
    }
}


function cancelAuth(){
event.preventDefault(); 
window.location = "../../nslogout";
}

function initForPermission() {
    if (globals.card) { return; }
    globals.step = Step.PERMISSION;
    document.getElementById("lblOPT").style.display = "none";
    const idTitle = 'title';
    const btnNextAuth = 'btnNextAuth';
	const headerPermission = 'headerPermission';

    const newTitle = `
    <div id="headerPermission" class="d-flex justify-content-center">
        <h1>רק רגע של תשומת לב </h1>
        <div class="align-items-center col-1 d-flex justify-content-center">
            <img class="w-75" aria-hidden="true" src="../../ShaamStylesLib/illustrations-icons/heart.png">
        </div>
    </div>`;
    const title = document.getElementById(idTitle);
	const header = document.getElementById(headerPermission);
	
	if(header){
	   header.remove();
	}

    const btnNext = document.getElementById("btnNextAuth");

	if (title) {
        $('#' + idTitle).empty();
		if(btnNext){
			$('#' + idTitle).after(newTitle);
		}	
    }
	
     $('#' + btnNextAuth).before('<button type="button" class="btn btn-secondary m-3" onclick="cancelAuth(event)">ביטול ההרשאה</button>');
     $('#' + btnNextAuth).addClass('btn btn-primary m-3 ps-4 pe-4');
    
    // const btnCancel = document.getElementById("btnCancelAuth");
    // btnCancel.classList.add("btn", "btn-secondary", "m-3");
    // btnCancel.click = (event) => {  event.preventDefault(); window.location = '../../nslogout'; }
    // btnCancel.href = "../../nslogout";
     
    const rows = document.querySelectorAll('.CredentialTypenone');
    rows.forEach(row => {
        row.classList.add('mb-4');
    });
}

function editStepOne() {
    if (globals.card) { return; }
    $(globalJQName.idPasswordJQ).after('<label for="passwd" id="infoPass" class="info-txt"> *קוד המשתמש שקיבלת בתהליך הרישום </label>');
    $(globalJQName.idTZJQ).after('<div id="IDErrMess" class="invalid-feedback d-block" aria-live="assertive"></div>');
    $(globalJQName.idPasswordJQ).after('<div id="passErrMess" class="invalid-feedback d-block" aria-live="assertive"></div>');

    const form = document.querySelector("form");
    const loginBtn = form.querySelector(".forms-authentication-button");
    loginBtn.classList.add("btn", "btn-primary", "w-100", "mt-5");
    loginBtn.onclick = chekForm;
    const tzField = form.querySelector(".CredentialTypeusername");
    const tzInput = tzField.querySelector("input");
    const passField = form.querySelector(".CredentialTypepassword");
    const passInput = passField.querySelector("input");
    const errField = form.querySelector(".CredentialTypenone");

    if (errField) {
        var str = $("div.detail-text.error").text();
        var str2 = "נתונים";
        if (str.indexOf(str2) !== 0) {
            $.get("/msgerr.html?" + globals.nsmsgid, (data) => {
                msgerr = data;
                document.getElementsByClassName('detail-text')[4].innerText = msgerr;
            });
        }
        $("#divMessage").append('<div role="alert" aria-live="assertive" class="alert-i alert-i--error bi ms-0 me-0">אחד או יותר מהפרטים הוקלדו בצורה שגויה, יש לתקן ולנסות שוב </div>');
    } else {
        $("#divMessage").empty();
    }

    tzInput.onkeyup = (e) => { validateTZ(e); }
    passInput.onkeyup = () => { validatePassword(); }

    function validatePassword() {
		let errHe = false;
		
		if(/[^A-Za-z0-9]/g.test(passInput.value)){
			passwordError("יש להזין אותיות באנגלית וספרות בלבד");
			errHe = true;
		}
		
        passInput.value = passInput.value.replace(/[^A-Za-z0-9]/g, '');

        if (passInput.value === "" && globals.submited) {
            passwordError("שדה חובה");
        } else if(!errHe){
            passwordError("");
        }
    }

    function validateTZ(e) {
        let tz = tzInput.value;
        if (tz === "" && globals.submited) {
            tzError("שדה חובה");
            return;
        }
        let error = false;
        if (tz.length > 9 || tz === 0 || isNaN(tz)) { error = true; }
        let tmpTZ = parseInt(tz);
        let digits = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        let oneTwo = [1, 2, 1, 2, 1, 2, 1, 2, 1];
        let result = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        // Start filling array from the end
        let i = 8;
        while (tmpTZ > 0) {
            digits[i] = tmpTZ % 10;
            tmpTZ = parseInt(tmpTZ / 10);
            i--;
        }
        for (let j = 0; j < digits.length; j++) {
            let tmpResult = (digits[j] * oneTwo[j]);
            // If number is greater than 9, add both digits
            if (tmpResult > 9) {
                tmpResult -= 9;
            }
            result[j] = tmpResult;
        }
        let iResult = 0;
        for (var x = 0; x < result.length; x++) {
            iResult = iResult + result[x];
        }

        if ((iResult % 10) !== 0) { error = true; }

        (error) ? tzError("מספר זהות שגוי") : tzError("");
    }

    function tzError(message) {
        let errTxt = tzField.querySelector(".invalid-feedback");
        if (message !== "") {
            tzInput.classList.add(globalName.invalidClass)
            tzInput.setAttribute("aria-invalid", "true");
            tzInput.focus();
        }
        else {
            tzInput.classList.remove(globalName.invalidClass);
            tzInput.setAttribute("aria-invalid", "false");
        }
        errTxt.innerText = message;
    }

    function passwordError(message) {
        let errTxt = passField.querySelector(".invalid-feedback");
        if (message !== "") {
            passInput.classList.add(globalName.invalidClass);
            if (tzField.querySelector(".invalid-feedback") === null || tzField.querySelector(".invalid-feedback").innerText === "") {
                passInput.focus();
            }
        } else {
            passInput.classList.remove(globalName.invalidClass);
        }
        errTxt.innerText = message;
    }

    function chekOnlyNumbers(event) {
        if (event.keyCode == 13 || event.which == 13) {
            tzError("יש להזין ספרות בלבד");
            return false;
        }

        var key_codes = [0, 8, 13, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
        var regex = new RegExp("^[0-9]");
        var regexKeys = new RegExp("^[0,13,46,8]");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (!(regex.test(str) || ($.inArray(e.which, key_codes) >= 0) || (regexKeys.test(str)))) {
            tzError("יש להזין ספרות בלבד");
            return false;
        }
        return true;
    }

    function chekForm() {
        globals.submited = true;
        (tzInput.value === "") ? tzError("שדה חובה") : validateTZ();
        // (passInput.value === "") ? passwordError("שדה חובה") : validatePassword();
        validatePassword();
    }
}

function editStepTwo() {
    if (globals.card) {
        return;
    }
    let passValid = false;

    $(globalJQName.idPassword2JQ).after('<label id="passErrMess" class="info-txt"><i class="me-2 bi bi-clock" aria-hidden="true"></i>קוד האימות תקף ל-10 דקות</label>');
    $(globalJQName.idPassword2JQ).after('<div class="invalid-feedback d-block"></div>');

    const form = document.querySelector("form");
    const loginBtn = form.querySelector(".forms-authentication-button");

    loginBtn.classList.add("btn", "btn-primary", "w-100", "mt-5");
    loginBtn.onclick = chekForm;

    const passField = form.querySelector(".CredentialTypepassword");
    const passInput = passField.querySelector("input");
    passInput.setAttribute("aria-describedby","passErrMess");
    passInput.setAttribute('aria-invalid','false');
	// Listener to the input while tpying while we have an error
	passInput.addEventListener('input', function() {
	const divInsideDivMessage = document.getElementById('divMessage').querySelector('div');

		// Check if the div has the role 'alert'
		if(divInsideDivMessage.getAttribute('role') === 'alert'){
			divInsideDivMessage.className = '';
			divInsideDivMessage.removeAttribute('role');
			divInsideDivMessage.innerText = '';
		}
	});
	
    const errField = form.querySelector(".CredentialTypenone");
	
    if (errField) {
        $.get("/msgerr.html?" + globals.nsmsgid, (data) => {
            msgerr = data;
            document.getElementsByClassName('detail-text')[4].innerText = globals.nsmsgid;
            // errText.innerText = msgerr;
			passValid = true;
            if(passValid){
		$("#divMessage").append('<div role="alert" aria-live="assertive" class="alert-i alert-i--error bi ms-0 me-0">' + msgerr + '</div>');
		passInput.setAttribute('aria-invalid','true');
	    } else {
		validatePassword();
	}
        });
    } else {
	passInput.setAttribute('aria-invalid','false');
        $("#divMessage").empty();
	passValid = false;
    }


    passInput.onkeyup = () => { validatePassword(); }

    function validatePassword() {
		/*if(/[^A-Za-z0-9]/g.test(passInput.value)){
			passwordError("יש להזין אותיות באנגלית וספרות בלבד");
			passValid = false;
		}*/
		
	
		let invalid = passInput.value === "" || passInput.value.length < 4 || /[^A-Za-z0-9]/g.test(passInput.value);		
		
        if (invalid) {
			if(/[^A-Za-z0-9]/g.test(passInput.value)){
				passwordErrorStepTwo("יש להזין אותיות באנגלית וספרות בלבד");
				passInput.value = passInput.value.replace(/[^A-Za-z0-9]/g, '');			
			} 
            else if (passInput.value === "") {
                passwordErrorStepTwo("שדה חובה");    
            } else if (passInput.value.length < 4){
				passwordErrorStepTwo("קוד חייב להיות בן 4 ספרות לפחות");   
			} else if(globals.submited){
                    passwordErrorStepTwo("קוד בפורמט שגוי");
            }
            //  !loginBtn.classList.contains('disabled') ? loginBtn.classList.add("disabled") : void (0);
            // loginBtnN.hasAttribute('disabled') ? loginBtnN.setAttribute("disabled", "true") : void (0);
            passValid = false;
			passInput.focus();
        } else if (!invalid) {
            passwordErrorStepTwo("");
            //  loginBtn.classList.remove("disabled");
            // loginBtnN.removeAttribute("disabled");
            passValid = true;
        }
    }

    function passwordErrorStepTwo(message) {
        let errTxt = passField.querySelector(".invalid-feedback");
        message !== "" ? passInput.classList.add(globalName.invalidClass) : passInput.classList.remove(globalName.invalidClass);
        errTxt.innerText = message;
    }

    function chekForm() {
        globals.submited = true;
        validatePassword();
    }
}

function editStepPermissions() {
    if (globals.card) { return; }
	
	document.getElementById("dUnauthorized").classList.remove("d-none");
	
    const lblReg = document.getElementById("lblReg");
	if(lblReg && !lblReg.classList.contains("d-none")){
		lblReg.classList.add("d-none");
	}
	
    const forgotCode = document.getElementById("forgotCode");
    if(forgotCode && !forgotCode.classList.contains("d-none")){
		forgotCode.classList.add("d-none");
	}

    const divIn = document.querySelector(".p-size-in");
    if (divIn)
        divIn.classList.remove('text-start');
}

function getCookie(cname) {
    const name = cname + "=";
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function cancelAuth(event) {
  event.preventDefault();
  window.location = "../../nslogout";
}


function initForm() {
    switch (globals.step) {
        case Step.FULL_LOGIN:
            editStepOne()
            break;
        case Step.LOGIN_VERIFICATION:
            editStepTwo();
            break;
        case Step.PERMISSION:
            editStepPermissions();
            break;
        default:
            break;
    }
}

const reload = () => {
    globals.step = '';
    window.location = globals.nextPage;
}

const goTOStep1 = () => {
    window.location = "../../nsstep1";
    return false;
}


